<template>
  <div class="app-container" style="padding-top: 0" v-loading="loading">
    <!-- 移动端骨架屏 -->
    <mobile-skeleton 
      v-if="isMobile && loading" 
      :showHeader="true"
      :showTable="true"
      :tableColumns="3"
      :tableRows="5"
      :showPagination="total > 0"
    />
    
    <div v-else>
      <!-- 头部返回区域 -->
      <el-row :gutter="10" class="test_header" type="flex" align="middle" justify="start">
        <el-col :span="1">
          <img :src="backImg" style="width: 25px; height: 25px; cursor: pointer; margin-left: 10px"
            @click="handleBack" /></el-col>
        <el-col :span="23">
          <h3 :style="{ color: theme }">考试统计</h3>
        </el-col>
      </el-row>
      
      <!-- 桌面端布局 -->
      <div v-if="!isMobile">
        <el-form ref="postForm" label-position="left" label-width="120px">
          <el-card style="padding-top: 20px">
            <el-descriptions class="margin-top" :column="3" border>
              <el-descriptions-item v-if="data.name && data.name !== undefined">
                <template slot="label"> 考试名称 </template>
                {{ data.name }}
              </el-descriptions-item>
              <el-descriptions-item v-if="data && data.course !== undefined && data.course.name !== undefined">
                <template slot="label"> 关联课程 </template>
                {{ data.course.name }}
              </el-descriptions-item>
              <el-descriptions-item v-if="data.start_time !== undefined && data.end_time !== undefined">
                <template slot="label"> 考试时间 </template>
                {{ data.start_time }} 至 {{ data.end_time }}
              </el-descriptions-item>
              <el-descriptions-item v-if="data.user !== undefined">
                <template slot="label"> 应参考人数 </template>
                {{ data.user.length }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">考试合格人数 </template>
                {{ passeds.length }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 考试状态 </template>
                <el-tag size="small"> {{ data.state | stateFilter }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
          
          <!-- 明细 -->
          <h3 :style="{ color: theme }">明细情况</h3>
          <el-card style="margin-top: 20px">
            <div class="table-operations">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
            </div>
            <el-table :data="data.user" style="width: 100%; margin-bottom: 20px" row-key="id" border size="mini">
              <el-table-column label="序号" min-width="40">
                <template slot-scope="scope">
                  {{ (queryParams.page - 1) * queryParams.page_size + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="员工" width="180">
                <template slot-scope="scope">
                  {{ scope.row.name }}
                </template>
              </el-table-column>
              <el-table-column label="部门" width="180">
                <template slot-scope="scope">
                  {{ scope.row.dept }}
                </template>
              </el-table-column>
              <el-table-column label="岗位" width="220">
                <template slot-scope="scope">
                  <span v-if="scope.row.post && scope.row.post.length > 0">{{ scope.row.post[0].name }}</span>
                  <span v-else>暂无关联岗位</span>
                </template>
              </el-table-column>
    
              <el-table-column label="关联课程" v-if="data.course !== undefined && data.course.name !== undefined"> {{
                data.course.name
              }} </el-table-column>
              <el-table-column label="考试次数">
                <template slot-scope="scope">
                  {{ scope.row.paper_list.count }}
                </template>
              </el-table-column>
              <el-table-column label="历史最高分">
                <template slot-scope="scope">
                  {{Math.floor((scope.row.paper_list.max*(data.total_score/data.question_count))*100 )/100}}
                </template>
              </el-table-column>
              <el-table-column label="考试结果">
                <template slot-scope="scope">
                  <span :style="scope.row.paper_list.is_passed == false ? { color: 'red' } : { color: theme }"> {{
                    scope.row.paper_list.is_passed | passedFilter }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-form>
      </div>
      
      <!-- 移动端布局 -->
      <div v-if="isMobile" class="mobile-statistics-view">
        <!-- 考试基本信息卡片 -->
        <el-card shadow="hover" class="stat-card">
          <div class="card-header">
            <div class="card-title" :style="{ color: theme }">{{ data.name }}</div>
          </div>
          
          <div class="info-list">
            <div class="info-item" v-if="data && data.course !== undefined && data.course.name !== undefined">
              <span class="label">关联课程：</span>
              <span class="value">{{ data.course.name }}</span>
            </div>
            <div class="info-item" v-if="data.start_time !== undefined && data.end_time !== undefined">
              <span class="label">考试时间：</span>
              <span class="value">{{ data.start_time }} 至 {{ data.end_time }}</span>
            </div>
            <div class="info-item" v-if="data.user !== undefined">
              <span class="label">应参考人数：</span>
              <span class="value">{{ data.user.length }}</span>
            </div>
            <div class="info-item">
              <span class="label">合格人数：</span>
              <span class="value" :style="{ color: theme, fontWeight: 'bold' }">{{ passeds.length }}</span>
            </div>
            <div class="info-item">
              <span class="label">考试状态：</span>
              <span class="value"><el-tag size="small">{{ data.state | stateFilter }}</el-tag></span>
            </div>
          </div>
          
          <!-- 导出按钮 -->
          <div class="export-action">
            <el-button type="warning" plain icon="el-icon-download" size="small" @click="handleExport" style="width: 100%">
              导出统计数据
            </el-button>
          </div>
        </el-card>
        
        <!-- 明细情况 -->
        <h3 :style="{ color: theme, marginTop: '15px', paddingLeft: '10px', borderLeft: `4px solid ${theme}` }">
          明细情况
        </h3>
        
        <!-- 移动端人员列表 -->
        <div class="mobile-user-list">
          <el-card v-for="(item, index) in data.user" :key="index" class="user-card" shadow="hover">
            <div class="user-info">
              <div class="user-name">
                {{ item.name }}
                <span class="user-index">#{{ (queryParams.page - 1) * queryParams.page_size + index + 1 }}</span>
              </div>
              <div class="user-result" 
                :style="item.paper_list.is_passed ? { color: theme } : { color: 'red' }">
                {{ item.paper_list.is_passed | passedFilter }}
              </div>
            </div>
            
            <div class="user-details">
              <div class="detail-item">
                <span class="label">部门：</span>
                <span class="value">{{ item.dept }}</span>
              </div>
              <div class="detail-item">
                <span class="label">岗位：</span>
                <span class="value" v-if="item.post && item.post.length > 0">{{ item.post[0].name }}</span>
                <span class="value" v-else>暂无关联岗位</span>
              </div>
              <div class="detail-item">
                <span class="label">考试次数：</span>
                <span class="value">{{ item.paper_list.count }}</span>
              </div>
              <div class="detail-item">
                <span class="label">历史最高分：</span>
                <span class="value highlight" :style="item.paper_list.is_passed ? { color: theme } : {}">
                  {{Math.floor((item.paper_list.max*(data.total_score/data.question_count))*100 )/100}}
                </span>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import RepoSelect from "@/components/RepoSelect";
import { mapGetters, mapState } from "vuex";
import { examDetail } from "@/api/vadmin/exam/exam";
import variables from "@/assets/styles/variables.scss";
import backImg from "@/assets/images/back.png";
// 导入导出所需的库
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
import "@/assets/styles/mobile/exam.scss";
import MobileSkeleton from "@/components/MobileSkeleton";

export default {
  name: "ExamDetail",
  components: { RepoSelect, MobileSkeleton },
  data() {
    return {
      loading: true,
      backImg: backImg,
      postForm: { course: { name: "", id: "" }, user: [] },
      queryParams: {
        page_size: 10,
        page: 1,
      },
      passeds: [],
      is_passeds: {
        false: "不合格",
        true: "合格",

      },
     examId: '',
      data: [],
      plan_data: [],//应参加培训人员
      isMobile: false,
      mediaQueryList: null,
      total: 0,
      scoreChart: null,
      resultChart: null,
    };
  },
  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  watch: {},
  filters: {
    stateFilter(val) {
      const state = {
        0: "考试未开始",
        1: "考试中",
        2: "考试结束",
      };
      return state[val];
    },
    passedFilter(val) {
      const is_passed = {
        false: "未通过",
        true: "已通过",
        null: "未通过",
      };
      return is_passed[val];
    },
  },
  created() {
    if (this.$route.query.exam) {
      this.examId = this.$route.query.exam
  
      // console.log(999, this.$route.query)
      // this.getTrainData()
      this.getTrainCount()
    }
  },
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
    
    // 销毁图表实例
    if (this.scoreChart) {
      this.scoreChart.dispose();
    }
    if (this.resultChart) {
      this.resultChart.dispose();
    }
  },
  methods: {
  
    getTrainCount() {
      examDetail(this.examId).then(res => {
        // console.log(888, res)
        this.loading = false
        this.data = res
        this.data.user.forEach((item) => {
          if (item.paper_list.is_passed == true) {
            this.passeds.push(item);
          }
        });
      })
    },
    passedFormatter(row) {
      return this.is_passeds[row.is_passed];
    },
    handleBack() {
      this.$router.back()//返回浏览器上一页，并保留上一页数据
    },
    handleExport() {
      this.$confirm('确认导出考试统计数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'info',
          message: '正在导出数据，请稍候...'
        });
        
        // 设置表头和字段名
        const tHeader = ['序号', '员工', '部门', '岗位', '关联课程', '考试次数', '历史最高分', '考试结果'];
        const filterVal = ['index', 'name', 'dept', 'post', 'course', 'count', 'maxScore', 'passed'];
        
        // 格式化数据
        const list = this.data.user.map((item, index) => {
          return {
            index: index + 1,
            name: item.name,
            dept: item.dept,
            post: item.post && item.post.length > 0 ? item.post[0].name : '暂无关联岗位',
            course: this.data.course && this.data.course.name ? this.data.course.name : '暂无关联课程',
            count: item.paper_list.count,
            maxScore: Math.floor((item.paper_list.max*(this.data.total_score/this.data.question_count))*100 )/100,
            passed: item.paper_list.is_passed ? '已通过' : '未通过'
          };
        });
        
        // 导出Excel
        this.exportToExcel(tHeader, filterVal, list);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        });
      });
    },
    exportToExcel(tHeader, filterVal, list) {
      try {
        // 格式化表格数据
        const data = this.formatJson(filterVal, list);
        
        // 创建包含考试基本信息的前两行，确保与tHeader列数一致
        const examInfo = [
          ['考试名称', this.data.name || '', '关联课程', this.data.course && this.data.course.name ? this.data.course.name : '', '考试时间', `${this.data.start_time || ''} 至 ${this.data.end_time || ''}`, '', ''],
          ['应参考人数', this.data.user ? this.data.user.length : 0, '考试合格人数', this.passeds.length, '考试状态', this.getExamState(this.data.state), '', '']
        ];
        
        // 添加表头和数据
        const allData = [...examInfo, ['','','','','','','',''], tHeader, ...data];
        
        // 创建工作簿和工作表
        const ws = XLSX.utils.aoa_to_sheet(allData);
        const wb = XLSX.utils.book_new();
        
        // 设置列宽
        const wscols = tHeader.map((col, index) => {
          // 根据内容设置列宽
          let maxLength = 15; // 默认宽度
          allData.forEach(row => {
            const cellValue = row[index] ? row[index].toString() : '';
            const cellLength = cellValue.toString().charCodeAt(0) > 255 
              ? cellValue.length * 2 // 中文宽度加倍
              : cellValue.length;
            maxLength = Math.max(maxLength, cellLength);
          });
          return { wch: maxLength + 2 }; // 额外增加一些宽度
        });
        
        ws['!cols'] = wscols;
        
        // 添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        
        // 生成文件名
        const fileName = `考试统计_${this.data.name || '详情'}_${new Date().getTime()}.xlsx`;
        
        // 导出文件
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        saveAs(new Blob([wbout], { type: 'application/octet-stream' }), fileName);
        
        this.$message({
          message: '导出成功',
          type: 'success'
        });
      } catch (error) {
        console.error('导出失败:', error);
        this.$message({
          message: '导出失败，请重试',
          type: 'error'
        });
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    getExamState(val) {
      const state = {
        0: "考试未开始",
        1: "考试中",
        2: "考试结束",
      };
      return state[val];
    },
    getList() {
      this.loading = true;
      examDetail(this.examId, this.queryParams).then(response => {
        this.detailData = response;
        this.total = response.papers_count;
        this.loading = false;
        
        // 初始化图表
        this.$nextTick(() => {
          this.initScoreChart();
          this.initResultChart();
        });
      });
    },
    initScoreChart() {
      // 初始化成绩分布图表
      this.scoreChart = echarts.init(document.getElementById('scoreChart'));
      
      // 计算成绩分布
      const scoreRanges = [
        { min: 0, max: 60, label: '0-60分' },
        { min: 60, max: 70, label: '60-70分' },
        { min: 70, max: 80, label: '70-80分' },
        { min: 80, max: 90, label: '80-90分' },
        { min: 90, max: 100, label: '90-100分' }
      ];
      
      const scoreData = scoreRanges.map(range => {
        const count = this.detailData.papers.filter(paper => {
          const score = paper.score * 100;
          return score >= range.min && score <= range.max;
        }).length;
        
        return {
          name: range.label,
          value: count
        };
      });
      
      const option = {
        title: {
          text: '成绩分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: scoreRanges.map(range => range.label)
        },
        series: [
          {
            name: '成绩分布',
            type: 'pie',
            radius: '50%',
            data: scoreData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      this.scoreChart.setOption(option);
    },
    initResultChart() {
      // 初始化考试结果分布图表
      this.resultChart = echarts.init(document.getElementById('resultChart'));
      
      const passCount = this.detailData.pass_count;
      const failCount = this.detailData.count - this.detailData.pass_count;
      
      const option = {
        title: {
          text: '考试结果分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['及格', '不及格']
        },
        series: [
          {
            name: '考试结果',
            type: 'pie',
            radius: '50%',
            data: [
              { value: passCount, name: '及格' },
              { value: failCount, name: '不及格' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      this.resultChart.setOption(option);
    },
    viewDetail(row) {
      this.$router.push({
        path: `/vadmin/exam/paperDetail/${row.id}`
      });
    },
    exportExcel() {
      // 导出Excel功能
      this.$message.success('导出Excel功能待实现');
    },
    handleSizeChange(val) {
      this.queryParams.page_size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    }
  },
};
</script>

<style lang="scss" scoped>
.pre-exam div {
  line-height: 42px;
  color: #555555;
}

.post-tree {
  border: 1px solid #dcdfe6;
}

.el-tree {
  z-index: 2;
}

.ct_table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px !important;
  padding: 10px 0;

  tr {
    height: 40px;
  }

  td {}

  .tb_head {
    font-size: 16px;
    font-weight: 400;
    width: 140px;
    padding: 10px 0;
    background: #e4e4e4;
    padding-left: 20px;
  }

  .custom-table-td {
    width: 200px;
    font-size: 16px;
    font-weight: 400;
    color: #333333;
    padding: 10px 20px 10px;
  }

  .w180 {
    width: 180px;
  }
}

.table-operations {
  margin-bottom: 10px;
  text-align: right;
}

/* 移动端样式 */
.mobile-statistics-view {
  padding: 0 5px;
}

.stat-card {
  border-radius: 8px;
  margin-bottom: 10px;
}

.card-header {
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 15px;
  padding-bottom: 10px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.info-list {
  margin-bottom: 15px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.label {
  width: 90px;
  color: #606266;
  font-weight: 500;
}

.value {
  flex: 1;
  color: #303133;
}

.export-action {
  margin-top: 15px;
  border-top: 1px dashed #ebeef5;
  padding-top: 15px;
}

.mobile-user-list {
  margin-bottom: 60px;
}

.user-card {
  border-radius: 8px;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.user-name {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.user-index {
  font-size: 12px;
  color: #909399;
  margin-left: 5px;
  font-weight: normal;
}

.user-result {
  font-weight: bold;
}

.user-details {
  margin-top: 10px;
}

.detail-item {
  display: flex;
  margin-bottom: 8px;
}

.highlight {
  font-size: 16px;
  font-weight: bold;
}
</style>
